package xian_cheng;

import java.util.concurrent.*;

/***
 *@title CallableTest
 *@description <TODO description class purpose>
 *@author 许文迪
 *@version 1.0.0
 *@create 2025/5/27 14:47
 **/
public class CallableTest {

    static class Task implements Callable<String> {
        @Override
        public String call() throws Exception {
            System.out.println("CallableTest线程启动了");
            System.out.println("CallableTest线程等待中");
            System.out.println("当前线程为:"+Thread.currentThread().getName());
            System.out.println("当前活跃线程数:"+Thread.activeCount());
            Thread.sleep(2000);
            System.out.println("CallableTest线程结束");
            return "CallableTest返回值输出";
        }
    }

    public static void main(String[] args) {
        // 创建一个 Callable 任务
        Callable<String> callable = new Task();

        //实现方式1【线程池】
        // 创建一个线程池
        ExecutorService executorService = Executors.newFixedThreadPool(2);
        Future<String> submit = executorService.submit(callable);
        try {
            String result = submit.get();
            System.out.println("实现方式1【线程池】结果:"+result);
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
        //  关闭线程池
        executorService.shutdown();

        System.out.println("=========================分割线==============================");


        //实现方式2【FutureTask包装】
        // 使用 FutureTask 包装 Callable
        FutureTask<String> futureTask = new FutureTask<>(callable);
        // 创建线程并启动
        Thread thread = new Thread(futureTask);
        thread.start();
        try {
            // 获取任务的返回值
            String result = futureTask.get(); // 阻塞等待任务完成
            System.out.println("实现方式2【FutureTask包装】结果: " + result);
        } catch (Exception e) {
            e.printStackTrace();
        }


        System.out.println("主线程结束");
    }
}
